<template>
  <div class="sku-labeling-container">
    <el-row :gutter="20">
      <!-- 左侧任务列表 -->
      <el-col :span="8">
        <el-card class="task-list">
          <template #header>
            <div class="card-header">
              <span>待标注任务</span>
              <div>
                <el-input
                  v-model="search"
                  placeholder="搜索商品名"
                  style="width: 200px; margin-right: 10px;"
                  @keyup.enter="fetchTasks"
                >
                  <template #append>
                    <el-button @click="fetchTasks">
                      <el-icon><Search /></el-icon>
                    </el-button>
                  </template>
                </el-input>
                <el-button type="primary" @click="handleBatchLabel" :disabled="!selectedTasks.length">
                  批量标注
                </el-button>
              </div>
            </div>
          </template>
          
          <el-table
            :data="taskList"
            @selection-change="handleSelectionChange"
            height="calc(100vh - 280px)"
            @row-click="selectTask"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="item_name" label="商品名称" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag
                  :type="scope.row.cleaned_name ? 'success' : ''"
                  size="small"
                >
                  {{ scope.row.cleaned_name ? '已标注' : '待标注' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="page"
              v-model:page-size="pageSize"
              :total="total"
              @current-change="fetchTasks"
              @size-change="fetchTasks"
              layout="total, sizes, prev, pager, next"
              :page-sizes="[10, 20, 50, 100]"
            />
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧标注区域 -->
      <el-col :span="16">
        <el-card v-if="currentTask" class="labeling-area">
          <template #header>
            <div class="card-header">
              <span>标注详情</span>
              <div>
                <el-button type="success" @click="handleAutoLabel">
                  自动标注
                </el-button>
                <el-button type="primary" @click="handleSave">
                  保存
                </el-button>
                <el-button @click="handleNext">
                  下一条
                </el-button>
              </div>
            </div>
          </template>
          
          <el-form :model="editForm" label-width="120px">
            <el-form-item label="商品名称">
              <div class="original-text">{{ currentTask.item_name }}</div>
            </el-form-item>
            
            <el-form-item label="品牌">
              <el-input v-model="editForm.item_brand" />
            </el-form-item>
            
            <el-form-item label="规格">
              <el-input v-model="editForm.item_specs" />
            </el-form-item>
            
            <el-form-item label="清洗后名称">
              <el-input v-model="editForm.cleaned_name" />
            </el-form-item>
            
            <el-form-item label="基础单位">
              <el-input v-model="editForm.base_unit" />
            </el-form-item>
          </el-form>
          
          <!-- 标注结果预览 -->
          <div class="label-results">
            <h4>标注结果预览：</h4>
            <el-table :data="[editForm]" border stripe style="margin-top: 10px;">
              <el-table-column label="原始名称" prop="item_name">
                <template #default>
                  <div class="highlight-diff">
                    <span>{{ currentTask.item_name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="品牌" prop="item_brand">
                <template #default="scope">
                  <div class="highlight-diff" :class="{ 'has-change': scope.row.item_brand !== currentTask.item_brand }">
                    <span>{{ scope.row.item_brand || '-' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="规格" prop="item_specs">
                <template #default="scope">
                  <div class="highlight-diff" :class="{ 'has-change': scope.row.item_specs !== currentTask.item_specs }">
                    <span>{{ scope.row.item_specs || '-' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="清洗后名称" prop="cleaned_name">
                <template #default="scope">
                  <div class="highlight-diff" :class="{ 'has-change': scope.row.cleaned_name !== currentTask.cleaned_name }">
                    <span>{{ scope.row.cleaned_name || '-' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="基础单位" prop="base_unit">
                <template #default="scope">
                  <div class="highlight-diff" :class="{ 'has-change': scope.row.base_unit !== currentTask.base_unit }">
                    <span>{{ scope.row.base_unit || '-' }}</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <div v-if="autoLabelResult" class="auto-label-result">
            <h4>自动标注建议：</h4>
            <el-descriptions :column="1" border>
              <el-descriptions-item v-if="autoLabelResult.item_brand" label="品牌">
                {{ autoLabelResult.item_brand }}
                <el-button link type="primary" @click="adoptSuggestion('item_brand')">
                  采用
                </el-button>
              </el-descriptions-item>
              <el-descriptions-item v-if="autoLabelResult.item_specs" label="规格">
                {{ autoLabelResult.item_specs }}
                <el-button link type="primary" @click="adoptSuggestion('item_specs')">
                  采用
                </el-button>
              </el-descriptions-item>
              <el-descriptions-item v-if="autoLabelResult.cleaned_name" label="清洗后名称">
                {{ autoLabelResult.cleaned_name }}
                <el-button link type="primary" @click="adoptSuggestion('cleaned_name')">
                  采用
                </el-button>
              </el-descriptions-item>
              <el-descriptions-item v-if="autoLabelResult.base_unit" label="基础单位">
                {{ autoLabelResult.base_unit }}
                <el-button link type="primary" @click="adoptSuggestion('base_unit')">
                  采用
                </el-button>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
        <el-empty v-else description="请选择待标注的SKU" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

// 状态定义
const search = ref('')
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const taskList = ref([])
const selectedTasks = ref([])
const currentTask = ref(null)
const autoLabelResult = ref(null)

const editForm = reactive({
  item_brand: '',
  item_specs: '',
  cleaned_name: '',
  base_unit: ''
})

// 获取任务列表
async function fetchTasks() {
  try {
    const res = await axios.get('/api/sku/list', {
      params: {
        page: page.value,
        page_size: pageSize.value,
        search: search.value
      }
    })
    taskList.value = res.data.items
    total.value = res.data.total
  } catch (error) {
    ElMessage.error(`获取任务列表失败: ${error.message}`)
  }
}

// 选择任务
function selectTask(row) {
  currentTask.value = row
  Object.assign(editForm, row)
  autoLabelResult.value = null
}

// 批量选择
function handleSelectionChange(selection) {
  selectedTasks.value = selection
}

// 自动标注
async function handleAutoLabel() {
  if (!currentTask.value) return
  
  try {
    const res = await axios.post('/api/sku/auto-label', {
      item_name: currentTask.value.item_name
    })
    
    if (res.data) {
      autoLabelResult.value = res.data
      ElMessage.success('自动标注完成，请检查结果')
    }
  } catch (error) {
    ElMessage.error(`自动标注失败: ${error.message}`)
  }
}

// 批量自动标注
async function handleBatchLabel() {
  if (!selectedTasks.value.length) return
  
  try {
    const res = await axios.post('/api/sku/auto-label', {
      batch_mode: true,
      item_ids: selectedTasks.value.map(t => t.id)
    })
    
    if (res.data) {
      ElMessage.success(res.data.message)
      fetchTasks()
    }
  } catch (error) {
    ElMessage.error(`批量标注失败: ${error.message}`)
  }
}

// 采用建议
function adoptSuggestion(field) {
  if (autoLabelResult.value && autoLabelResult.value[field]) {
    editForm[field] = autoLabelResult.value[field]
  }
}

// 保存
async function handleSave() {
  if (!currentTask.value) return
  
  try {
    await axios.post('/api/sku/update', {
      id: currentTask.value.id,
      item_name: currentTask.value.item_name,
      sku: currentTask.value.sku,
      ...editForm
    })
    
    ElMessage.success('保存成功')
    fetchTasks()
  } catch (error) {
    ElMessage.error(`保存失败: ${error.message}`)
  }
}

// 下一条
function handleNext() {
  const currentIndex = taskList.value.findIndex(t => t.id === currentTask.value?.id)
  if (currentIndex > -1 && currentIndex < taskList.value.length - 1) {
    selectTask(taskList.value[currentIndex + 1])
  } else {
    ElMessage.info('已是最后一条')
  }
}

// 初始化
fetchTasks()
</script>

<style scoped>
.sku-labeling-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-list {
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.original-text {
  font-size: 16px;
  color: #409EFF;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.auto-label-result {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.labeling-area {
  height: calc(100vh - 100px);
  overflow-y: auto;
}

.label-results {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.highlight-diff {
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.highlight-diff.has-change {
  background-color: #ecf5ff;
  color: #409EFF;
}

.highlight-diff span {
  font-family: monospace;
}
</style> 